<?php

namespace app\app\controller;

use app\app\model\ProjectBuildingSiteInfoModel;
use app\app\model\ProjectBuildingSiteModel;
use app\app\model\ProjectIntoModel;
use app\app\model\ProjectMatterModel;
use app\app\model\ProjectTicketVideoModel;
use app\app\model\ProjectWarningModel;
use app\app\model\ProjectBuildingTicketModel;
use app\app\model\ProjectRiskModel;
use app\app\model\RandModel;
use app\BaseController;
use app\Request;

class ProjectBuildingSite extends BaseController
{

    public function index(Request $request)
    {

    }

    public function analysis()
    {
        $project_id = input('project_id', '');
        $start_time = date('Y-m-d 00:00:00', time());
        $end_time = date('Y-m-d  23:59:59', time());
        $where_into[] = ['into_time', 'BETWEEN', [$start_time, $end_time]];
        $where[] = ['project_id', '=', $project_id];
        //安装设备个数
        $data['facility_total'] = ProjectBuildingSiteInfoModel::where($where)->count();

        //异常设备个数
        $data['facility_total_warn'] = ProjectBuildingSiteInfoModel::where($where)->where('state', 2)->count();
        //当天报警个数
        $data['alarm_total'] = ProjectWarningModel::where($where)
            ->where('alarm_time', 'BETWEEN', [$start_time, $end_time])->count();


        //在场人数
        $data['present_total'] = ProjectIntoModel::where($where)->where($where_into)->where('type', '在场')->count('id');
        //进场人数
        $data['come_total'] = ProjectIntoModel::where($where)->where($where_into)->where('type', '到岗')->count('id');

        //作业票数
        $data['ticket_total'] = ProjectBuildingTicketModel::where($where)->where('ticket_state', '执行中')->count('id');
        //风险数
        $where[] = ['start_time', '<=', $end_time];
        $where[] = ['end_time', '>=', $start_time];
        $data['risk_total'] = ProjectRiskModel::where($where)
            ->where('risk_level', '<=', 3)->count();

        $this->success('success', $data);
    }

    public function ticketList()
    {
        $project_id = input('project_id', '');
        $ticket_name = input('ticket_name', '');
        $where = "a.project_id = '" . $project_id . "'";
        if ($ticket_name) $where .= " AND a.ticket_name LIKE '%" . $ticket_name . "%'";
//        $list = ProjectBuildingTicketModel::alias('a')->field('a.*,b.file_name,b.file_name,b.file_path,c.file_path as technical_plan_file_path')
//            ->leftjoin('sys_file_info b', 'b.file_id = a.file_id')
//            ->leftjoin('sys_file_info c', 'c.file_id = a.technical_plan_file_id')
//            ->where($where)->where('ticket_state', '执行中')->select();
        $list = ProjectBuildingTicketModel::alias('a')->where($where)->where('ticket_state', '执行中')->select();
        $this->success('success', $list);
    }

    public function list()
    {
        $data = $this->request->param();
        $page_size = input('pageSize', '20');
        if (!$data['project_id']) $this->error('请传入id');
        $where[] = ['project_id', '=', $data['project_id']];

        if (isset($data['type']) && !empty($data['type'])) {
            if ($data['type'] == '摄像设备') {
                $where[] = ['type', 'in', ['摄像头', '布控球', '球机摄像头']];
            } else {
                $where[] = ['type', '=', $data['type']];
            }

        }
        if (isset($data['state']) && !empty($data['state'])) $where[] = ['state', '=', $data['state']];

        $list = ProjectBuildingSiteInfoModel::where($where)->select();
        $this->success('success', $list);
    }

    public function info()
    {
        $project_id = input('project_id', '');

        $where = [];
        if ($project_id) {
            $where[] = ['project_id', '=', $project_id];
        }
        $list = [];
        if (count($where)) {
            $list = ProjectBuildingSiteModel::where($where)->find();
            $info_list = ProjectBuildingSiteInfoModel::where($where)->where('state', '=', 1)->order('sort asc')->select();
            $ticket_count = ProjectBuildingTicketModel::where($where)->count();
        }
        $list['info'] = $info_list;
        $list['ticket_total'] = $ticket_count;
        $this->success('success', $list);
    }

    /**
     * 智慧工地信息记录
     * @param Request $request
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add(Request $request)
    {
        $data = $request->param();
        $data['id'] = RandModel::randId();
        $device_info = array();
        $camera_info = array();


//        type:摄像头或布控球  state：1正常  2：异常
//        array(
//            ['name' => '南岸摄像头', 'content' => '北岸项目部', 'type' => '摄像头','state'=>'1'],
//            ['name' => '布控球', 'content' => '封城项目部', 'type' => '布控球','state'=>'1']
//        );


        if (isset($data['camera_info'])) {
            $camera_info = json_decode($data['camera_info'], true);
        }

        unset($data['camera_info']);
        $data['update_time'] = date('Y-m-d H:i:s', time());
        $pbs = ProjectBuildingSiteModel::where('project_id', $data['project_id'])->find();
        if ($pbs) {
            $pbs->save($data);
        } else {
            ProjectBuildingSiteModel::create($data);
        }
        $todo_task_list = array();
        $pbsi_model = new \app\app\model\ProjectBuildingSiteInfoModel;
        if (count($camera_info)) {
            foreach ($camera_info as $key => $value) {
                $item['project_id'] = $data['project_id'];
                $item['building_site_id'] = $data['id'];
                $item['name'] = $value['name'];
                $item['content'] = $value['content'];
                $item['type'] = $value['type'];
                $item['state'] = $value['state'];

                $pbsi_camera = $pbsi_model->where('project_id', $data['project_id'])->where('type', '摄像头')
                    ->where('type', $value['type'])
                    ->where('name', $value['name'])->find();
                if ($pbsi_camera) {
                    $pbsi_camera->save($item);
                } else {
                    array_push($todo_task_list, $item);
                }
            }
        }
        if (count($todo_task_list)) {
            $res = $pbsi_model->saveAll($todo_task_list, false);
        }
        $this->success('success');
    }

    /**
     * 智慧工地设备添加
     */
    public function siteAdd()
    {
        $data = $this->request->param();
//        type:摄像头或布控球  state：1正常  2：异常
//        $data['site_info'] = array(
//            ['name' => '南岸摄像头', 'content' => '北岸项目部', 'type' => '摄像头', 'state' => '1'],
//            ['name' => '布控球', 'content' => '封城项目部', 'type' => '布控球', 'state' => '1']
//        );
        if (isset($data['site_info'])) {
            $camera_info = json_decode($data['site_info'], true);
            $todo_task_list = array();
            $ProjectBuildingSiteInfoModel = new \app\app\model\ProjectBuildingSiteInfoModel;
            if (count($camera_info)) {
                foreach ($camera_info as $value) {
                    $item['project_id'] = $data['project_id'];
                    $item['name'] = $value['name'];
                    $item['content'] = $value['content'];
                    $item['type'] = $value['type'];
                    $item['state'] = $value['state'];
                    $pbsi_camera = $ProjectBuildingSiteInfoModel->where('project_id', $data['project_id'])
                        ->where('type', $value['type'])
                        ->where('name', $value['name'])->find();
//                    var_dump(ProjectBuildingSiteInfoModel::getLastSql());die();
                    if ($pbsi_camera) {
                        $pbsi_camera->save($item);
                    } else {
                        array_push($todo_task_list, $item);
                    }
                }
            }
            if (count($todo_task_list)) {
                $res = $ProjectBuildingSiteInfoModel->saveAll($todo_task_list, false);
            }
            $this->success('success');
        }
        $this->error('参数错误！');
    }

    /**
     * 智慧工地报警添加
     */
    public function reportAdd()
    {
        $data = $this->request->param();
//        $aa = array(
//            ['image_url' => '图片地址', 'name' => '北岸项目部', 'alarm_time' => '2021-07-22'],
//            ['image_url' => '图片地址', 'name' => '封城项目部', 'alarm_time' => '2021-12-24']
//        );
//        var_dump(json_encode($aa));die();

        $info = json_decode($data['info'], true);

        $warn_model = new \app\app\model\ProjectWarningModel;
        $todo_task_list = array();
        foreach ($info as $key => $value) {
            $item['image_url'] = $value['image_url'];
            $item['name'] = $value['name'];
            $item['alarm_time'] = $value['alarm_time'];
            $item['project_id'] = $data['project_id'];
            $item['create_time'] = date('Y-m-d H:i:s', time());
            array_push($todo_task_list, $item);
        }
        if (count($todo_task_list)) {
            $warn_model->saveAll($todo_task_list, false);
        }
        $this->success('success');
    }


    /**
     * 智慧工地报警列表
     */
    public function reportList()
    {
        $page_size = input('pageSize', '20');
        $project_id = input('project_id', '');
        $where[] = ['project_id', '=', $project_id];
        $start_time = date('Y-m-d 00:00:00', time());
        $end_time = date('Y-m-d  23:59:59', time());
        $where[] = ['alarm_time', 'BETWEEN', [$start_time, $end_time]];
        $list = ProjectWarningModel::where($where)->paginate($page_size);
        $this->success('success', $list);
    }

    /**
     * 智慧工地获取设备相关信息列表
     */
    public function deviceList()
    {
        $type = input('type', '1');
        $project_id = input('project_id', '');
        $where[] = ['project_id', '=', $project_id];
        if ($type == 2) {
            $where[] = ['state', '=', 2];
        } elseif ($type == 3) {
            $where[] = ['type', '=', '布控球'];
        } else {
        }
        $list = ProjectBuildingSiteInfoModel::where($where)->select();
        $this->success('success', $list);
    }


    /**
     * 智慧工地在场以及到岗人员更新
     */
    public function buildInto()
    {
        $data = $this->request->param();
//        $aa = array(
//            ['name' => '刘亮', 'department' => '北岸项目部', 'into_time' => '2021-07-22', 'user_type' => '分包', 'type' => '到岗'],
//            ['name' => '黄云天', 'department' => '封城项目部', 'into_time' => '2021-12-24', 'user_type' => '分包', 'type' => '在场']
//        );
        $info = json_decode($data['info'], true);
        $pi_model = new \app\app\model\ProjectIntoModel;
        $todo_task_list = array();
        $start_time = date('Y-m-d 00:00:00', time());
        $end_time = date('Y-m-d  23:59:59', time());

        $pi_model->where('into_time', 'BETWEEN', [$start_time, $end_time])->where('project_id', $data['project_id'])->delete();

        foreach ($info as $key => $value) {
            $item['name'] = $value['name'];
            $item['department'] = $value['department'];
            $item['into_time'] = $value['into_time'] ? $value['into_time'] : '';
            $item['user_type'] = $value['user_type'];
            $item['project_id'] = $data['project_id'];
            $item['type'] = $value['type'];
            array_push($todo_task_list, $item);
        }

        if (count($todo_task_list)) {
            $pi_model->saveAll($todo_task_list, false);
        }

        $this->success('success');
    }


    public function ticketAdd()
    {
        $data = $this->request->param();
        ProjectBuildingTicketModel::create($data);
        $this->success('success');
    }


    public function ticketsAdd()
    {
//        $arr = array(
//            ['ticket_id' => '32178', 'construction_name' => '工作地区', 'ticket_level' => '作业票等级', 'danger_level' => '风险级别','ticket_position'=>'作业部位',
//                'ticket_name'=>'作业票名称',
//                'ticket_quantity'=>'78', 'ticket_content'=>'作业内容',
//                'begin_time' => '2022-03-09 00:00:00', 'end_time' => '2022-03-20 00:00:00', 'real_quantity' => '15', 'ticket_man' => '作业负责人',
//                'ticket_state' => '执行中', 'ticket_url' => 'http://58.215.235.2:11102/profile/upload/2021/08/13/c51cc348-3fdc-4450-ae39-a4fc266bbe9e.pdf',
//                 'technical_plan_url'=>'http://58.215.235.2:11102/profile/upload/2021/08/13/c51cc348-3fdc-4450-ae39-a4fc266bbe9e.pdf',
//                  'video_url'=>'http://58.215.235.2:11102/profile/upload/2021/08/13/c51cc348-3fdc-4450-ae39-a4fc266bbe9e.pdf'],
//            ['ticket_id' => '321789', 'construction_name' => '工作地区', 'ticket_level' => '作业票等级', 'danger_level' => '风险级别','ticket_position'=>'作业部位',
//                'ticket_name'=>'作业票名称',
//                'ticket_quantity'=>'78', 'ticket_content'=>'作业内容',
//                'begin_time' => '2022-03-09 00:00:00', 'end_time' => '', 'real_quantity' => '15', 'ticket_man' => '作业负责人',
//                'ticket_state' => '执行中', 'ticket_url' => 'http://58.215.235.2:11102/profile/upload/2021/08/13/c51cc348-3fdc-4450-ae39-a4fc266bbe9e.pdf',
//                'technical_plan_url'=>'http://58.215.235.2:11102/profile/upload/2021/08/13/c51cc348-3fdc-4450-ae39-a4fc266bbe9e.pdf',
//                'video_url'=>'http://58.215.235.2:11102/profile/upload/2021/08/13/c51cc348-3fdc-4450-ae39-a4fc266bbe9e.pdf'],
//        );

//        var_dump(json_encode($arr));die();

        $data = $this->request->param();
        $info = json_decode($data['info'], true);
        $ProjectBuildingTicketModel = new \app\app\model\ProjectBuildingTicketModel;

        $ProjectBuildingTicketModel->where('project_id', $data['project_id'])->delete();
        $todo_task_list = array();

        foreach ($info as $key => $value) {
            $item = [];
            $item['project_id'] = $data['project_id'];
            $item['ticket_id'] = $value['ticket_id'];

            //作业票pdf
            $item['file_path'] = $value['ticket_url'];
            //施工pdf
            $item['technical_plan_file_path'] = $value['technical_plan_url'];

            $item['construction_name'] = $value['construction_name'];
            $item['ticket_level'] = $value['ticket_level'];
            $item['danger_level'] = $value['danger_level'];
            $item['ticket_position'] = $value['ticket_position'];
            $item['ticket_name'] = $value['ticket_name'];
            $item['ticket_quantity'] = $value['ticket_quantity'];
            $item['ticket_content'] = $value['ticket_content'];
            if (isset($value['begin_time']) && !empty($value['begin_time'])) {
                $item['begin_time'] = $value['begin_time'];
            }
            if (isset($value['end_time']) && !empty($value['end_time'])) {
                $item['end_time'] = $value['end_time'];
            }
            $item['real_quantity'] = $value['real_quantity'];
            if (isset($value['ticket_man']) && !empty($value['ticket_man'])) {
                $item['ticket_man'] = $value['ticket_man'];
            }
            $item['ticket_state'] = $value['ticket_state'];
            $item['oper_time'] = date('Y-m-d H:i:s');

            array_push($todo_task_list, $item);
            $video_url = $value['video_url'] ? $value['video_url'] : '';
            if ($video_url) {
                $videoArr['ticket_id'] = $item['ticket_id'];
                $videoArr['project_id'] = $item['project_id'];
                $videoArr['video_url'] = $value['video_url'];
                $videoArr['create_time'] = date('Y-m-d H:i:s');
                ProjectTicketVideoModel::create($videoArr);
            }
        }
        if (count($todo_task_list)) {
            $res = $ProjectBuildingTicketModel->saveAll($todo_task_list, false);
        }
        if ($res) {
            $this->success('添加成功');
        }
        $this->error('添加失败');

    }


    public function videoAdd()
    {
        $project_id = input('project_id');
        $ticket_id = input('ticket_id');
        $audio_file = input('audio_file');

        $audio_arr = explode(',', $audio_file);
        $ProjectTicketVideoModel = new \app\app\model\ProjectTicketVideoModel;
        $todo_task_list = [];
        foreach ($audio_arr as $value) {
            $videoArr['ticket_id'] = $ticket_id;
            $videoArr['project_id'] = $project_id;
            $videoArr['video_url'] = $value;
            $videoArr['create_time'] = date('Y-m-d H:i:s');
            array_push($todo_task_list, $videoArr);
        }

        if (count($todo_task_list)) {
            $ProjectTicketVideoModel->saveAll($todo_task_list, false);
        }
        $this->success('添加成功');

    }

    public function videoList()
    {
        $project_id = input('project_id');
        $ticket_id = input('ticket_id');
        $page_size = input('pageSize', '20');
        $list = ProjectTicketVideoModel::where('project_id', $project_id)
            ->where('ticket_id', $ticket_id)->paginate($page_size);
        $this->success('success', $list);
    }


    /**
     * 风险数量 当日和总数  作业票数量 总数和当日
     * @return void
     */
    public function census()
    {
        $project_id = input('project_id');
        $where[] = ['project_id', '=', $project_id];

        $start_time = date('Y-m-d 00:00:00', time());
        $end_time = date('Y-m-d 23:59:59', time());

        //当天风险数
        $where_risk_today[] = ['start_time', '<=', $end_time];
        $where_risk_today[] = ['end_time', '>=', $start_time];
        $risk_total = ProjectRiskModel::where($where_risk_today)->where($where)
            ->where('risk_level', '<=', 3)->count();
        //风险总数
        $risk_today = ProjectRiskModel::where($where)
            ->where('risk_level', '<=', 3)->count();

        //当天作业票数
        $ticket_today = ProjectBuildingTicketModel::where($where)->where('ticket_state', '执行中')->count('id');
        //作业票总数
        $ticket_total = ProjectBuildingTicketModel::where($where)->where('ticket_state', '执行中')->count('id');

        $list = array(
            'risk_total' => $risk_total,
            'risk_today' => $risk_today,
            'ticket_total' => $ticket_total,
            'ticket_today' => $ticket_today,
        );
        $this->success('success', $list);
    }


}
